package com.dogkr.server.web;

import java.io.File;
import java.util.List;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.ResultPath;

import com.dogkr.common.Constants;
import com.dogkr.common.ServerAction;
import com.sean.common.utils.FileUtils;
import com.sean.common.utils.StringUtils;

// 设置Struts2注解
@ParentPackage(value = "login-default")
@Namespace(value = "/tools")
@InterceptorRefs(value = {@InterceptorRef("fileUploadStack")})
@ResultPath("/WEB-INF/jsps")
@Action(value = "upload")
public class FileUploadAction extends ServerAction {
	private static final long serialVersionUID = 1L;

	/** 文件对象 */
	private List<File> filedata;
	/** 文件名 */
	private List<String> filedataFileName;
	/** 文件内容类型 */
	private List<String> filedataContentType;

	@Override
	public String execute() throws Exception {
		try {
			// 如果上传类型为空或者上传文件为空直接返回上传页面
			if (filedata == null || filedata.size() == 0) {
				res = new PageResult(-1, "文件上传出错！未发现上传文件。");
			} else {
				String fileName = filedataFileName.get(0);
				String ext = FileUtils.getExtention(fileName);
				if(StringUtils.equalsIgnoreCase(ext, ".jpg", ".png", ".gif")) {
					File newFile = new File(Constants.UPLOAD_PATH_TEMP, FileUtils.getNewFileName(fileName));
					FileUtils.copyFile(filedata.get(0), newFile);
					res.put("sourceName", fileName);
					res.put("fileName", newFile.getName());
				} else {
					res = new PageResult(-1, "文件上传出错！文件类型错误。");
				}
			}
		} catch (Exception e) {
			res = new PageResult(-1, "文件上传出错！未知异常。");
			log.error("文件上传出错.", e);
			this.setStatus(500);
		}
		finally {
			outJson(res);
		}
		return null;
	}
	
	
	
	public List<File> getFiledata() {
		return filedata;
	}

	public void setFiledata(List<File> filedata) {
		this.filedata = filedata;
	}

	public List<String> getFiledataFileName() {
		return filedataFileName;
	}

	public void setFiledataFileName(List<String> filedataFileName) {
		this.filedataFileName = filedataFileName;
	}

	public List<String> getFiledataContentType() {
		return filedataContentType;
	}

	public void setFiledataContentType(List<String> filedataContentType) {
		this.filedataContentType = filedataContentType;
	}
}